{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 打开文件\n",
    "f = open('test.txt', 'w')\n",
    "\n",
    "# 2.文件写入\n",
    "f.write('hello world')\n",
    "\n",
    "# 3. 关闭文件\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['hello world\\n', 'abcdefg\\n', 'aaa\\n', 'bbb\\n', 'ccc']\n"
     ]
    }
   ],
   "source": [
    "f = open('test1.txt')\n",
    "content = f.readlines()\n",
    "\n",
    "# ['hello world\\n', 'abcdefg\\n', 'aaa\\n', 'bbb\\n', 'ccc']\n",
    "print(content)\n",
    "\n",
    "# 关闭文件\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第一行：hello world\n",
      "\n",
      "第二行：abcdefg\n",
      "\n"
     ]
    }
   ],
   "source": [
    "f = open('test1.txt')\n",
    "\n",
    "content = f.readline()\n",
    "print(f'第一行：{content}')\n",
    "\n",
    "content = f.readline()\n",
    "print(f'第二行：{content}')\n",
    "\n",
    "# 关闭文件\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文件备份"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入您要备份的文件名：test1.txt\n"
     ]
    }
   ],
   "source": [
    "old_name = input('请输入您要备份的文件名：')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.1 提取文件后缀点的下标\n",
    "index = old_name.rfind('.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'test1'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "old_name[:index]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_name = old_name[:index] + '[备份]' + old_name[index:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'test1[备份].txt'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3.1 打开文件\n",
    "old_f = open(old_name, 'rb')\n",
    "new_f = open(new_name, 'wb')\n",
    "\n",
    "\n",
    "# 3.2 将源文件数据写入备份文件\n",
    "while True:\n",
    "    con = old_f.read(1024)\n",
    "    if len(con) == 0:\n",
    "        break\n",
    "    new_f.write(con)\n",
    "'''\n",
    "若不确定目标文件大小，循环读取写入；当读取出来的数据没有了，终止循环\n",
    "'''\n",
    "\n",
    "# 3.3 关闭文件\n",
    "old_f.close()\n",
    "new_f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 思考"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "old_name = input('请输入您要备份的文件名：')\n",
    "\n",
    "index = old_name.rfind('.')\n",
    "\n",
    "# 有效文件才备份\n",
    "if index > 0:\n",
    "    postfix = old_name[index:]\n",
    "\n",
    "new_name = old_name[:index] + '[备份]' + postfix\n",
    "\n",
    "old_f = open(old_name, 'rb')\n",
    "new_f = open(new_name, 'wb')\n",
    "\n",
    "while True:\n",
    "    con = old_f.read(1024)\n",
    "    if len(con) == 0:\n",
    "        break\n",
    "    new_f.write(con)\n",
    "\n",
    "old_f.close()\n",
    "new_f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 应用案例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Python-.ipynb_checkpoints', 'Python-test.txt', 'Python-test1.txt', 'Python-test1[备份].txt', 'Python-文件操作.ipynb']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# 设置重命名标识：如果为1则添加指定字符，flag取值为2则删除指定字符\n",
    "flag = 2\n",
    "\n",
    "# 获取指定目录\n",
    "dir_name = './'\n",
    "\n",
    "# 获取指定目录的文件列表\n",
    "file_list = os.listdir(dir_name)\n",
    "print(file_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ".ipynb_checkpoints\n",
      "test.txt\n",
      "test1.txt\n",
      "test1[备份].txt\n",
      "文件操作.ipynb\n"
     ]
    }
   ],
   "source": [
    "# 遍历文件列表内的文件\n",
    "for name in file_list:\n",
    "    \n",
    "    \n",
    "    # 添加指定字符\n",
    "    if flag == 1:\n",
    "        new_name = 'Python-' + name\n",
    "    # 删除指定字符\n",
    "    elif flag == 2:\n",
    "        num = len('Python-')\n",
    "        new_name = name[num:]\n",
    "\n",
    "    # 打印新文件名，测试程序正确性\n",
    "    print(new_name)\n",
    "    \n",
    "    # 重命名\n",
    "    os.rename(dir_name+name, dir_name+new_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "82e3d5622aba4b69a60db331bab679c5c2bf6b9202990cd11811da1e2a094d5c"
  },
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
